package member.initial;

import common.totalInfo.*;
import last.tomsquare.*;
import common.db.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;


import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

public class Login extends Activity 
{
	
	
	/** Called when the activity is first created. */
	
	Button btnloggin;
	String id, pw;
	String xml;
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
	    super.onCreate(savedInstanceState);
	    
	   
	    setContentView(R.layout.emallogin);
	    // TODO Auto-generated method stub
	    
	    btnloggin = (Button)findViewById(R.id.btnlogin);
	    btnloggin.setOnClickListener(On_Login);
	}
	
	
	
	private View.OnClickListener On_Login = new View.OnClickListener()
	{
			
		@Override
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub
				
			id = ((EditText)(findViewById(R.id.editemail))).getText().toString(); 
	        pw = ((EditText)(findViewById(R.id.editpass))).getText().toString(); 
		        
	        Hashtable loginResult = HttpPostData();
	        String result = (String)loginResult.get("result");
	        String code = (String)loginResult.get("code");
		        
	        if(result.equals("success"))
		    {
	        	TomSquareDBMethod dbe = new TomSquareDBMethod(Login.this);
		       	String selectQuery = "SELECT code FROM member WHERE email = '"+id+"'";
		       	Cursor cursor = dbe.select(selectQuery);
		       	String test = cursor.getCount()+"";
		       	
		       	if(cursor.getCount() == 0)
		       	{
		       		String query = "INSERT INTO member VALUES (null, '"+code+"', '"+id+"', '"+pw+"', 'Y')";
		       		dbe.insert(query);
		       	}
		        cursor.close();
		       	
		        Toast.makeText(Login.this, test, 0).show();
		       	
		        Toast.makeText(Login.this, "로그인 성공", 0).show();
		       	Intent intent = new Intent(Login.this, MenuButton.class);
		       	startActivity(intent);
		       	finish();
		    }
		    else
		    {
		    	Toast.makeText(Login.this, "로그인 실패", 0).show();
		    }
			    
		        //Toast.makeText(Login.this, "전송 완료", 0).show();
				//Intent j = new Intent(Login.this, MenuButton.class);
				//j.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//startActivity(j);
		}
	 };
	 
	 
	 
	  public Hashtable HttpPostData() 
	  {
	
		 Hashtable loginResult = new Hashtable();
		 
         try {
              //--------------------------
              //   URL 설정하고 접속하기
              //--------------------------
              URL url = new URL("http://192.168.43.206/app/Login.jsp");       // URL 설정
              HttpURLConnection http = (HttpURLConnection) url.openConnection();   // 접속
              //--------------------------
              //   전송 모드 설정 - 기본적인 설정이다
              //--------------------------
              http.setDefaultUseCaches(false);                                           
              http.setDoInput(true);                         // 서버에서 읽기 모드 지정
              http.setDoOutput(true);                       // 서버로 쓰기 모드 지정 
              http.setRequestMethod("POST");         // 전송 방식은 POST

              // 서버에게 웹에서 <Form>으로 값이 넘어온 것과 같은 방식으로 처리하라는 걸 알려준다
              http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              //--------------------------
              //   서버로 값 전송
              //--------------------------
              StringBuffer buffer = new StringBuffer();
              buffer.append("id").append("=").append(id).append("&");
              buffer.append("pw").append("=").append(pw);
            
              OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
              PrintWriter writer = new PrintWriter(outStream);
              writer.write(buffer.toString());
              writer.flush();
              //--------------------------
              //   서버에서 전송받기
              //--------------------------
              InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8"); 
              BufferedReader reader = new BufferedReader(tmp);
              StringBuilder builder = new StringBuilder();
 
              String str;
              while ((str = reader.readLine()) != null) {       // 서버에서 라인단위로 보내줄 것이므로 라인단위로 읽는다
                   builder.append(str);                     // View에 표시하기 위해 라인 구분자 추가
              }
             xml = builder.toString();                       // 전송결과를 전역 변수에 저장
             
             
             loginResult = xmlParser(xml);
             
             String result = (String)loginResult.get("result");
             
             Toast.makeText(Login.this, result, 0).show();
         } 
         catch (MalformedURLException e) {
                //
         } 
         catch (IOException e) {
                // 
         } // try
         
         return loginResult;
         
	  } // HttpPostData
	  
	  
	  
	  
	  public Hashtable xmlParser(String xmlVal)
	  {
		Hashtable resultTable = new Hashtable();
		  
		boolean resultItem = false;
		boolean codeItem = false;
		String result = "";
		String code = "";

		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(new StringReader(xmlVal));
			
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.END_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					if (parser.getName().equals("result")) {
						resultItem = true;
					}
					if(parser.getName().equals("code"))
					{
						codeItem = true;
					}
					break;
				case XmlPullParser.END_TAG:
					break;
				case XmlPullParser.TEXT:
					if (resultItem) 
					{
						result = parser.getText();
						resultItem = false;
					}
					if(codeItem)
					{
						code = parser.getText();
						codeItem = false;
					}
					break;
				}
				eventType = parser.next();
			}
		}
		catch (Exception e) {
			Toast.makeText(Login.this, e.getMessage(), 0).show();
		}
		
		resultTable.put("result", result);
		resultTable.put("code", code);
		
		return resultTable;
	}
}
